//
//  MVVM_BaseViewController.swift
//  MVVM_BaseViewController
//
//  Created by alyadan on 2016/10/13.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import YD_Util
import QMUIKit

open class MVVM_BaseViewController: QMUICommonViewController , MVVM_ViewProtocol, UIGestureRecognizerDelegate{
    
    open var myBag: [String: Any]?
    open var currentModel: MVVM_BaseViewModel? {
        return vcModel.value
    }
    
    public enum navItemLocation {
        case left
        case right
    }
    
    //    public static var viewBackgroundColor:UIColor?
    public static var navBackImageName:String?
    public static var viewBGImage:UIImage?
    //    public static var statusStyle: UIStatusBarStyle = .default
    
    public var disposeBag = DisposeBag()
    
    public var vcModel = Variable<MVVM_BaseVCModel?>(nil)
    
    public var customLeftBarButton: QMUINavigationButton?
    public var customRightBarButton: QMUINavigationButton?
    
    //MARK: MVVM_ViewProtocol
    open func bindModelData() {
        
    }
    
    open func addActionTarget() {
        
    }
    
    open func setupUI() {
        
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        
        //        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        
        #if DEBUG
            print("Number of start resources = \(Resources.total)")
        #endif
        
        if let x = MVVM_BaseViewController.viewBGImage {
            let imageView = UIImageView(image: x)
            view.addSubview(imageView)
            imageView.frame = view.bounds;
        }
        
        vcModel.asObservable().bind { [unowned self] (x:MVVM_BaseVCModel?) in
            x?.MVVM_modelController = self
            x?.bindDataModel()
            }.addDisposableTo(disposeBag)
        
        
        
        setupBaseViewController()
        setupUI()
        addActionTarget()
        bindModelData()
    }
    
    deinit {
        print("\(self) deinit")
        NotificationCenter.default.removeObserver(self)
    }
    
    
    private func setupBaseViewController() {
        
        vcModel.asObservable()
            .filter{$0 != nil}
            .map{$0!}
            .flatMapLatest{$0.viewControllerTitle.asObservable()}
            .map{$0 ?? ""}
            .bind(to: self.rx.title)
            .addDisposableTo(disposeBag)
        
        if presentingViewController != nil && self.navigationController?.viewControllers.first == self {
            self.setNavgationItem(withImageName: MVVM_BaseViewController.navBackImageName ?? "nav_back", orTitle: nil, location: .left)
        }
    }
    
    
    public func setNavgationItem(withImageName imageName:String?, orTitle title:String?, location: navItemLocation = .right) {
        
        guard imageName != nil || title != nil else {
            print("imageName and title are both nil")
            return
        }
        
        
        var button: UIBarButtonItem?
        var navBtn: QMUINavigationButton?
        if let imageName = imageName {
            let b = QMUINavigationButton(type: .image)
            b.setImage(UIImage.init(named: imageName), for: .normal)
            navBtn = b
            button = UIBarButtonItem.qmui_item(with: b, target: self, action:location == .left ? #selector(MVVM_BaseViewController.onTapNavLeftBtn) : #selector(MVVM_BaseViewController.onTapNavRightBtn) )
//            button = QMUINavigationButton.barButtonItem(with: b, position: location == .left ? .left : .right,target: self, action: location == .left ? #selector(MVVM_BaseViewController.onTapNavLeftBtn) : #selector(MVVM_BaseViewController.onTapNavRightBtn))
            
            //                        button = QMUINavigationButton.barButtonItem(with: UIImage.init(named: imageName), position: location == .left ? .left : .right, target: (self.currentModel as? MVVM_BaseVCModel), action: location == .left ? #selector(MVVM_BaseVCModel.onTapNavLeftBtn) : #selector(MVVM_BaseVCModel.onTapNavRightBtn) )
        }
        
        if let title = title {
            let b = QMUINavigationButton(type: .normal)
            b.setTitle(title, for: .normal)
            navBtn = b
            button = UIBarButtonItem.qmui_item(with: b, target: self, action:location == .left ? #selector(MVVM_BaseViewController.onTapNavLeftBtn) : #selector(MVVM_BaseViewController.onTapNavRightBtn) )

        }
        
        let barBtnItemAppearance = UIBarButtonItem.appearance()
        let barBtnItemAttr = barBtnItemAppearance.titleTextAttributes(for: .normal)
        
        
        
        navBtn?.titleLabel?.font = barBtnItemAttr?[NSAttributedString.Key.font] as? UIFont
        navBtn?.setTitleColor(barBtnItemAttr?[NSAttributedString.Key.foregroundColor] as? UIColor, for: .normal)
        navBtn?.setTitle(title, for: .normal)
        navBtn?.contentHorizontalAlignment = location == .left ? .left : .right
        
        if(location == .left){
            self.customLeftBarButton = navBtn
            navigationItem.leftBarButtonItem = button
        }else{
            self.customRightBarButton = navBtn
            navigationItem.rightBarButtonItem = button
        }
        
    }
    
//    open override func shouldCustomNavigationBarTransitionIfBarHiddenable() -> Bool {
//        return true
//    }
    
    open override func shouldCustomizeNavigationBarTransitionIfHideable() -> Bool {
        return true
    }
    
//    open override func shouldCustomNavigationBarTransitionWhenPopAppearing() -> Bool {
//        return true
//    }
//
//    open override func shouldCustomNavigationBarTransitionWhenPushAppearing() -> Bool {
//        return true
//    }
//
//    open override func shouldCustomNavigationBarTransitionWhenPopDisappearing() -> Bool {
//        return true
//    }
//
//    open override func shouldCustomNavigationBarTransitionWhenPushDisappearing() -> Bool {
//        return true
//    }
    
    //MARK: reactive action
    
    @objc open func onTapNavRightBtn() {
        (self.currentModel as? MVVM_BaseVCModel)?.onTapNavRightBtn()
    }
    
    @objc open func onTapNavLeftBtn() {
        (self.currentModel as? MVVM_BaseVCModel)?.onTapNavLeftBtn()
    }
}

